import { BasemapAction, BasemapActionTypes } from '../actions/basemaps.action';
import { Basemap } from '../../models';

export interface BasemapState {
    entities: { [id: string]: Basemap },
    checked: string;
    loaded: boolean;
    loading: boolean;
}

export const initialBasemapState = {
    entities: {},
    checked: null,
    loaded: false,
    loading: false
};

export function basemapsReducer(state: BasemapState = initialBasemapState, action: BasemapAction): BasemapState {
    switch(action.type) {
        case BasemapActionTypes.CHECKED_BASEMAPS: {
            return {
                ...state,
                checked: action.payload
            }
        }
        case BasemapActionTypes.LOAD_BASEMAPS: {
            return {
                ...state,
                loaded: false,
                loading: true
            }
        }
        case BasemapActionTypes.LOAD_BASEMAPS_FAIL: {
            return {
                ...state,
                loaded: false,
                loading: false
            }
        }
        case BasemapActionTypes.LOAD_BASEMAPS_SUCCESS: {
            let checked: string = null;
            const basemaps: Basemap[] = <Basemap[]>action.payload;
            const entities: { [id: string]: Basemap } = basemaps.reduce((entities: { [id: string]: Basemap }, basemap: Basemap) => {
                if(basemap.selected) checked = basemap.id;
                return { ...entities, [basemap.id]: basemap };
            }, {});
            return {
                ...state,
                entities,
                checked
            }
        }
        default: {
            return state;
        }
    }
}
